package com.hyyt.shopjsp.product.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.hyyt.shopjsp.basic.pojo.BasicUsers;
import com.hyyt.shopjsp.common.controller.BaseController;
import com.hyyt.shopjsp.product.pojo.ShopProductAttribute;
import com.hyyt.shopjsp.product.pojo.ShopProductImg;
import com.hyyt.shopjsp.product.pojo.ShopProductInfo;
import com.hyyt.shopjsp.product.pojo.ShopProductParameter;
import com.hyyt.shopjsp.product.pojo.ShopShopProCategoryRelation;
import com.hyyt.shopjsp.product.pojo.ShopSpecification;
import com.hyyt.shopjsp.product.pojo.ShopSpecificationValue;
import com.hyyt.shopjsp.product.service.IShopProductInfoService;
import com.hyyt.shopjsp.product.vo.ParamGroupInfoVo;
import com.hyyt.shopjsp.product.vo.ParamGroupVo;
import com.hyyt.shopjsp.product.vo.ProductAttrListVo;
import com.hyyt.shopjsp.product.vo.ProductImageListVo;
import com.hyyt.shopjsp.product.vo.SearchProductVo;
import com.hyyt.shopjsp.solr.service.ISolrService;
import com.hyyt.shopjsp.store.info.pojo.ShopShopCategory;
import com.hyyt.shopjsp.store.info.pojo.ShopShopInfo;
import com.hyyt.shopjsp.store.info.service.IShopShopCategoryService;
import com.hyyt.shopjsp.util.common.Page;
import com.hyyt.shopjsp.util.common.ResultMsg;
import com.hyyt.shopjsp.util.common.Utils;
import com.hyyt.shopjsp.util.json.FastJsonUtils;

/**
 * Copyright (c) 2017 ShopJsp. All Rights Reserved.
 * ============================================================================
 * 版权所有 2011 - 今 北京华宇盈通科技有限公司，并保留所有权利。
 * ----------------------------------------------------------------------------
 * 提示：在未取得SHOPJSP商业授权之前，您不能将本软件应用于商业用途，否则SHOPJSP将保留追究的权力。
 * ----------------------------------------------------------------------------
 * 官方网站：http://www.shopjsp.com
 * ============================================================================
 * @author Wang Youchun on 2017/04/24 0024上午 10:46.
 */

@Controller
@RequestMapping("/back/shopProduct")
public class ShopProductInfoController extends BaseController{
	
	private Logger log = Logger.getLogger(ShopProductInfoController.class);
	private String basePath = "/back/shop/product/shopProduct/";
	@Resource
	private IShopProductInfoService shopProductInfoService;//商品service

	@Resource
	private IShopShopCategoryService shopShopCategoryService;//商品service

    /**
     * 搜索商品
     */
    @Resource
    private ISolrService solrService;

	/**
	 * 根据店铺ID跳转到入驻店铺商品列表页
	 * @param param
	 * @return
	 */
	@RequestMapping("gotoEnterShopProductListPage")
	public String gotoEnterShopProductListPage( Map<String, Object> param){
		//查询店铺分类信息，用于添加商品选择店铺列表中查询
		List<ShopShopCategory> shopCategoryList=shopShopCategoryService.queryAllShopShopCategory();
		param.put("shopCategoryList", shopCategoryList);
		param.put("shopInfoProductType",2);
		param.put("shopInfoType",2);
		return basePath+"enterShopProductList";
	}

	/**
	 * 根据店铺ID跳转到自营店铺商品列表页
	 * @param param
	 * @return
	 */
	@RequestMapping("gotoSelfSupportShopProductListPage")
	public String gotoSelfSupportShopProductListPage( Map<String, Object> param){
		//查询店铺分类信息，用于添加商品选择店铺列表中查询
		List<ShopShopCategory> shopCategoryList=shopShopCategoryService.queryAllShopShopCategory();
		param.put("shopCategoryList", shopCategoryList);
		param.put("shopInfoProductType",1);
		param.put("shopInfoType",1);
		return basePath+"selfSupportShopProductList";
	}

	/**
	 * 根据店铺ID查询该店铺的商品
	 * @param page
	 * @param shopInfoProductType	店铺类型：1表示平台自营店铺 2表示入驻店铺
	 * @param productName	商品名称
	 * @param sku	商品
	 * @param isPass	审核状态
	 * @param isPutSale	是否上架
	 * @param imageType	图片类型
	 */
	@RequestMapping("queryProductList")
	@ResponseBody
	public void queryProductList(Page page,Integer shopInfoProductType,String productName,String sku,Integer isPass,Integer isPutSale,Integer imageType, HttpServletResponse response){
		Map<String, Object> param = new HashMap<>();
		if(Utils.objectIsNotEmpty(shopInfoProductType)){
			param.put("shopInfoProductType",shopInfoProductType);
		}
		if(Utils.objectIsNotEmpty(productName)){
			param.put("productName",productName.trim());
		}
		if(Utils.objectIsNotEmpty(sku)){
			param.put("sku",sku.trim());
		}
		if(Utils.objectIsNotEmpty(isPass)){
			param.put("isPass",isPass);
		}
		if(Utils.objectIsNotEmpty(isPutSale)){
			param.put("isPutSale",isPutSale);
		}
		if(Utils.objectIsNotEmpty(imageType)){
			param.put("imageType",imageType);
		}
		param.put("sortColumns", "productId desc");

		int totalRecordCount =shopProductInfoService.countShopProductInfo(param);
		page.setPageInfo(page.getPageSize(), totalRecordCount, page.getCurrentPage());
		List<Map<String,Object>> productInfoList =shopProductInfoService.queryShopProductInfo(param, page.getPageRecordBeginIndex(), page.getPageSize());
		param.clear();
		param.put("total", totalRecordCount);// total键 存放总记录数，必须的
		param.put("rows", productInfoList);// rows键 存放每页记录 list
		ResultMsg.create(param, response);  //把内容发送到页面
	}

	/**
	 * 保存或修改店铺信息
	 * @return
	 */
	@RequestMapping(value="saveOrUpdateShopInfoProduct",method= RequestMethod.POST)
	@ResponseBody
	public ResultMsg saveOrUpdateShopInfoProduct(Integer shopInfoId,Integer shopProCategoryId,ProductImageListVo productImageListVo, ShopProductInfo productInfo,  ParamGroupInfoVo paramGroupInfoVo, ParamGroupVo paramGroupVo, ProductAttrListVo productAttrListVo, String specifications, String detailContent ){
		boolean flag=true;
		if(Utils.objectIsNotEmpty(productInfo)){
			if(Utils.objectIsNotEmpty(productInfo.getProductId())){//修改操作
				shopProductInfoService.updateShopProductInfo(shopProCategoryId,productInfo,productImageListVo,productAttrListVo,paramGroupInfoVo,paramGroupVo,detailContent);
			}else{//添加操作
				shopProductInfoService.saveShopProductInfo(shopProCategoryId,productInfo,productImageListVo,productAttrListVo,paramGroupInfoVo, paramGroupVo,specifications,detailContent);
			}
		}else{
			flag=false;
		}
		return ResultMsg.create(flag);
	}

	/**
	 *商品详情页滚动图片上传
	 * @param productImageInfo 图片流对象
	 * @param subSysFolderName 子系统目录
	 * @param imageInfoPath 图片存放目录
	 * @return
	 */
	@RequestMapping("uploadProductImage")
	@ResponseBody
	public ResultMsg uploadProductImage(MultipartFile productImageInfo, String subSysFolderName,String imageInfoPath){
		ShopProductImg productImg = new ShopProductImg();
		productImg = shopProductInfoService.uploadProductImage(productImageInfo,subSysFolderName,imageInfoPath, productImg);
		return ResultMsg.create(true,"上传成功", FastJsonUtils.toJSONString(productImg));
	}

	/**
	 *删除商品组图信息
	 * @param productImageId 商品Id
	 * @return ResultMsg
	 */
	@RequestMapping("deleteProductImageByProductImageId")
	@ResponseBody
	public ResultMsg deleteProductImageByProductImageId(Integer productImageId){
		shopProductInfoService.deleteProductImageByProductImageId(productImageId);
		return ResultMsg.create(true);
	}

	/**
	 *通过商品分类Id查询对应所有商品的属性及值
	 * @param productTypeId 商品分类Id
	 * @return
	 */
	@RequestMapping("getProductAttributeAndValueList")
	@ResponseBody
	public void getProductAttributeAndValueList(Integer productTypeId, HttpServletResponse response){
		List<ShopProductAttribute> productAttributeList= shopProductInfoService.getProductAttributeAndValueList(productTypeId);
		Map<String, Object> params = new HashMap<>();
		params.put("productAttributeList",productAttributeList);
		ResultMsg.create(params,response);
	}

	/**
	 *通过商品分类Id查询对应所有商品的规格参数及值
	 * @param productTypeId 商品分类Id
	 * @return
	 */
	@RequestMapping("getProductParameterAndValueList")
	@ResponseBody
	public void getProductParameterAndValueList(Integer productTypeId, HttpServletResponse response){
		List<ShopProductParameter> productParameterList= shopProductInfoService.getProductParameterAndValueList(productTypeId);
		Map<String, Object> params = new HashMap<>();
		params.put("productParameterList",productParameterList);
		ResultMsg.create(params,response);
	}

	/**
	 * 异步获取指定规格的规格值
	 * @param specificationId 商品规格组Id
	 */
	@RequestMapping("getSpecificationValueListBySpecificationId")
	@ResponseBody
	public void getSpecificationValueListBySpecificationId(Integer specificationId, HttpServletResponse response) {
		List<ShopSpecificationValue> specificationValueList = shopProductInfoService.getSpecificationValueListBySpecificationId(specificationId);
		Map<String, Object> params = new HashMap<>();
		params.put("specificationValueList",specificationValueList);
		ResultMsg.create(params,response);
	}

	/**
	 *通过商品分类Id查询对应所有商品规格组及值
	 * @param productTypeId 商品分类Id
	 * @return
	 */
	@RequestMapping("getProductSpecificationList")
	@ResponseBody
	public void getProductSpecificationList(Integer productTypeId, HttpServletResponse response){
		List<ShopSpecification> productSpecificationList= shopProductInfoService.getProductSpecificationList(productTypeId);
		Map<String, Object> params = new HashMap<>();
		params.put("productSpecificationList",productSpecificationList);
		ResultMsg.create(params,response);
	}


	/**
	 *通过商品Id查询商品信息
	 * @param productId 商品Id
	 * @return
	 */
	@RequestMapping("getShopProductAndRelationInfoByProductId")
	@ResponseBody
	public void getShopProductAndRelationInfoByProductId(Integer productId, HttpServletResponse response){
		Map<String, Object> params  = shopProductInfoService.getShopProductAndRelationInfoByProductId(productId);
		ResultMsg.create(params,response);
	}

	/**
	 *通过商品Id查询商品店铺内部分类信息
	 * @param productId 商品Id
	 * @return
	 */
	@RequestMapping("getShopShopProCategoryRelationByProductId")
	@ResponseBody
	public void getShopShopProCategoryRelationByProductId(Integer productId, HttpServletResponse response){
		ShopShopProCategoryRelation shopProCategoryRelation = shopProductInfoService.getShopShopProCategoryRelationByProductId(productId);
		ResultMsg.create(shopProCategoryRelation,response);
	}

	/**
	 *通过规格Id查询规格对象信息
	 * @param specificationId 规格Id
	 * @return
	 */
	@RequestMapping("getShopSpecificationBySpecificationId")
	@ResponseBody
	public void getShopSpecificationBySpecificationId(Integer specificationId, HttpServletResponse response){
		ShopSpecification shopSpecification = shopProductInfoService.getShopSpecificationBySpecificationId(specificationId);
		ResultMsg.create(shopSpecification,response);
	}

	/**
	 *通过规格值Id查询规格值对象信息
	 * @param specificationValueId 规格值Id
	 * @return
	 */
	@RequestMapping("getShopSpecificationValueBySpecificationValueId")
	@ResponseBody
	public void getShopSpecificationValueBySpecificationValueId(Integer specificationValueId, HttpServletResponse response){
		ShopSpecificationValue shopSpecificationValue = shopProductInfoService.getShopSpecificationValueBySpecificationValueId(specificationValueId);
		ResultMsg.create(shopSpecificationValue,response);
	}

	/**
	 * 根据商品Id查询商品详情
	 * @param productId
	 * @param response
	 */
	@RequestMapping("getProductInfoById")
	@ResponseBody
	public void getProductInfoById(Integer productId,HttpServletResponse response){
		Map<String,Object> resultMap= shopProductInfoService.getProductInfoById(productId);
		ResultMsg.create(resultMap,response);
	}

	/**
	 * 商品审核操作
	 * @param shopProductInfo 页面传入的商品对象
	 */
	@RequestMapping(value="auditProduct",method = RequestMethod.POST)
	@ResponseBody
	public ResultMsg auditProduct(ShopProductInfo shopProductInfo){
		BasicUsers basicUsers=getSessionUsers();
		boolean success=shopProductInfoService.auditProduct(shopProductInfo,basicUsers.getUserName());

		if(shopProductInfo.getIsPass() != null && 1 == shopProductInfo.getIsPass()){
		    SearchProductVo vo = new SearchProductVo();
		    ShopProductInfo productInfo = shopProductInfoService.loadShopProductInfo(shopProductInfo.getProductId());
		    vo.setProductId(productInfo.getProductId());
		    vo.setShopInfoId(productInfo.getShopInfoId());
		    vo.setShopName(productInfo.getShopName());
//          vo.setCustomerName(shopInfo.getCustomerName());
		    vo.setBrandId(productInfo.getBrandId());
		    vo.setProductTypeId(productInfo.getProductTypeId());
		    vo.setProductFullName(productInfo.getProductFullName());
		    vo.setProductName(productInfo.getProductName());
		    vo.setDescrible(productInfo.getDescrible());
		    vo.setTotalSales(productInfo.getTotalSales());
		    vo.setMarketPrice(productInfo.getMarketPrice() == null ? 0D : productInfo.getMarketPrice().doubleValue());
		    vo.setSalesPrice(productInfo.getSalesPrice() == null ? 0D : productInfo.getSalesPrice().doubleValue());
		    vo.setMemberPrice(productInfo.getMemberPrice() == null ? 0D : productInfo.getMemberPrice().doubleValue());
		    vo.setLogoImg(productInfo.getLogoImg());
		    vo.setSku(productInfo.getSku());
		    vo.setCategory_level1(productInfo.getCategoryLevel1());
		    vo.setCategory_level2(productInfo.getCategoryLevel2());
		    vo.setCategory_level3(productInfo.getCategoryLevel3());
		    vo.setCategory_level4(productInfo.getCategoryLevel4());
		    vo.setCreateDate(productInfo.getCreateDate());
		    vo.setUpdateDate(productInfo.getUpdateDate());
		    vo.setPutSaleDate(productInfo.getPutSaleDate());
		    vo.setEvaluate(productInfo.getEvaluate());
		    vo.setGoodsCount(productInfo.getGoodsCount());
		    vo.setGoodEvaluate(productInfo.getGoodEvaluate());
		    //  vo.setIsSelfSupport(shopInfo);
		    try {
		        solrService.addItem(vo, 10);
		    } catch (Exception e) {
		        e.printStackTrace();
		        logger.error("删除solr中商品索引失败");
		    }
		}
		return ResultMsg.create(success);
	}

	/**
	 * 修改商品返利操作
	 * @param shopProductInfo
	 * @return
	 */
	@RequestMapping("updateProductRatio")
	@ResponseBody
	public ResultMsg updateProductRatio(ShopProductInfo shopProductInfo){
		boolean success=shopProductInfoService.updateProductRatio(shopProductInfo);
		return ResultMsg.create(success);
	}


	/**
	 * 批量生成二维码操作
	 * @param shopInfoProductType 店铺类型：1 自营，2 入驻
	 * @param response
	 */
	@RequestMapping("productInfoGeneratedQrCode")
	@ResponseBody
	public void productInfoGeneratedQrCode(Integer shopInfoProductType,HttpServletResponse response){
		Map<String,Object> resultMap=shopProductInfoService.productInfoGeneratedQrCode(shopInfoProductType,response);
		ResultMsg.create(resultMap,response);
	}

	/**
	 * 进入商品评价管理
	 * @return 进入指定页面
	 */
	@RequestMapping("gotoProEvaluateGoods")
	public String gotoEvaluateGoods(Integer productId,Map<String,Object> params){
		params.put("productId",productId);
		return basePath+"evaluateGoodsList";
	}

	/**
	 * 删除商品
	 * @param productId
	 * @return
	 */
	@RequestMapping("deleteProductAll")
	@ResponseBody
	public ResultMsg deleteProductAll(Integer productId){
		boolean success=shopProductInfoService.deleteProductAll(productId);

        SearchProductVo vo = new SearchProductVo();

        vo.setProductId(productId);

//      ShopShopInfo shopInfo = getSessionStore();
//      ShopProductInfo productInfo = productInfoService.loadInfoForId(productId, shopInfo.getShopInfoId());
//      vo.setProductId(productInfo.getProductId());
//      vo.setShopInfoId(productInfo.getShopInfoId());
//      vo.setShopName(productInfo.getShopName());
//      vo.setCustomerName(shopInfo.getCustomerName());
//      vo.setBrandId(productInfo.getBrandId());
//      vo.setProductTypeId(productInfo.getProductTypeId());
//      vo.setProductFullName(productInfo.getProductFullName());
//      vo.setProductName(productInfo.getProductName());
//      vo.setDescrible(productInfo.getDescrible());
//      vo.setTotalSales(productInfo.getTotalSales());
//      vo.setMarketPrice(productInfo.getMarketPrice() == null ? 0D : productInfo.getMarketPrice().doubleValue());
//      vo.setSalesPrice(productInfo.getSalesPrice() == null ? 0D : productInfo.getSalesPrice().doubleValue());
//      vo.setMemberPrice(productInfo.getMemberPrice() == null ? 0D : productInfo.getMemberPrice().doubleValue());
//      vo.setLogoImg(productInfo.getLogoImg());
//      vo.setSku(productInfo.getSku());
//      vo.setCategory_level1(productInfo.getCategoryLevel1());
//      vo.setCategory_level2(productInfo.getCategoryLevel2());
//      vo.setCategory_level3(productInfo.getCategoryLevel3());
//      vo.setCategory_level4(productInfo.getCategoryLevel4());
//      vo.setCreateDate(productInfo.getCreateDate());
//      vo.setUpdateDate(productInfo.getUpdateDate());
//      vo.setPutSaleDate(productInfo.getPutSaleDate());
//      vo.setEvaluate(productInfo.getEvaluate());
//      vo.setGoodsCount(productInfo.getGoodsCount());
//      vo.setGoodEvaluate(productInfo.getGoodEvaluate());
//      //  vo.setIsSelfSupport(shopInfo);
      try {
          solrService.deleteById(vo, 10);
      } catch (Exception e) {
          e.printStackTrace();
          logger.error("删除solr中商品索引失败");
      }
		return ResultMsg.create(success);
	}
}
